// src/main/java/com/bookmanager/controller/EditUserController.java
package com.bookmanager.controller;

import com.bookmanager.model.User;
import com.bookmanager.service.UserService;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;

@WebServlet("/admin/edit-user")
public class EditUserController extends HttpServlet {
    private UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("user");

        // 检查管理员权限
        if (currentUser == null || !"admin".equals(currentUser.getRole())) {
            response.sendRedirect("../login.jsp");
            return;
        }

        // 获取要编辑的用户ID
        String userId = request.getParameter("userId");
        if (userId == null || userId.trim().isEmpty()) {
            response.sendRedirect("user-management");
            return;
        }

        // 获取用户信息
        User editUser = userService.getUserById(userId);
        if (editUser == null) {
            request.setAttribute("message", "用户不存在");
            request.setAttribute("messageType", "error");
            response.sendRedirect("user-management");
            return;
        }

        // 设置到请求属性中
        request.setAttribute("editUser", editUser);
        request.getRequestDispatcher("/admin/user-edit.jsp").forward(request, response);
    }
}